package juc练习;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    private static Semaphore S = new Semaphore(5);

    public static void main(String[] args) {
        //模拟停车场同时停车，但不能超出有限的车位数量
        for (int i = 0; i < 20; i++) {
            final int j = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取一个车位
                        S.acquire();
                        //停车以后做其他事情
                        System.out.println(j);
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        //出停车场，归还车位
                        S.release();
                    }
                }
            }).start();
        }
    }
}
